<template>
  <div class="common-list comp-orders" v-loading.fullscreen="loading">
    <div class="common-list__head">
      <el-input
        class="filter"
        v-model="filters.companyName"
        size="small"
        style="width: 320px"
        clearable
        placeholder="请输入"
        :readonly="loading"
        @change="search(true)"
      >
        <span slot="prepend">企业/项目名称</span>
      </el-input>
      <el-select
        class="filter"
        v-model="filters.companyCityId"
        size="small"
        style="width: 160px"
        @change="search(true)"
      >
        <el-option label="不限所在城市" :value="null"></el-option>
        <template v-for="data in citys">
          <el-option
            :key="data.id"
            :label="data.name"
            :value="data.id"
          ></el-option>
        </template>
      </el-select>
      <el-select
        class="filter"
        v-model="filters.companyCountyId"
        size="small"
        style="width: 160px"
        @change="search(true)"
      >
        <el-option label="不限所在县区" :value="null"></el-option>
        <template v-for="data in countys">
          <el-option
            :key="data.id"
            :label="data.name"
            :value="data.id"
            v-if="data.city.id === filters.companyCityId"
          ></el-option>
        </template>
      </el-select>
      <el-input
        class="filter"
        v-model="filters.title"
        size="small"
        style="width: 280px"
        clearable
        placeholder="请输入"
        :readonly="loading"
        @change="search(true)"
      >
        <span slot="prepend">事项标题</span>
      </el-input>
      <el-input
        class="filter"
        v-model="filters.content"
        size="small"
        style="width: 280px"
        clearable
        placeholder="请输入"
        :readonly="loading"
        @change="search(true)"
      >
        <span slot="prepend">事项描述</span>
      </el-input>
      <!--            <el-select class="filter" v-model="filters.handId" size="small" style="width: 240px" @change="search(true)">-->
      <!--                <el-option label="不限负责工作队" :value="null"></el-option>-->
      <!--                <el-option v-for="data in depts" :key="data.id" :label="data.name" :value="data.id"></el-option>-->
      <!--                <div class="el-select-dropdown__item" @click="chooseDept()">选择工作队</div>-->
      <!--            </el-select>-->
      <el-select
        class="filter"
        v-model="filters.tagId"
        size="small"
        style="width: 160px"
        @change="search(true)"
      >
        <el-option label="不限事项分类" :value="null"></el-option>
        <el-option
          v-for="data in tags"
          :key="data.id"
          :label="data.name"
          :value="data.id"
        ></el-option>
      </el-select>
      <el-select
        class="filter"
        v-model="filters.level"
        size="small"
        style="width: 160px"
        @change="search(true)"
      >
        <el-option label="不限层级" :value="null"></el-option>
        <el-option key="1" label="区县级" value="1"></el-option>
        <el-option key="2" label="市级" value="2"></el-option>
        <el-option key="3" label="自治区级" value="3"></el-option>
      </el-select>
      <el-select
        class="filter"
        v-model="filters.fwxz"
        size="small"
        style="width: 160px"
        @change="search(true)"
      >
        <el-option label="不限小组" :value="null"></el-option>
        <el-option
          key="17"
          label="市县自主调研"
          value="市县自主调研"
        ></el-option>

        <el-option key="0" label="第一组" value="第一组"></el-option>
        <el-option key="1" label="第二组" value="第二组"></el-option>
        <el-option key="2" label="第三组" value="第三组"></el-option>
        <el-option key="3" label="第四组" value="第四组"></el-option>
        <el-option key="4" label="第五组" value="第五组"></el-option>
        <el-option key="5" label="第六组" value="第六组"></el-option>
        <el-option key="6" label="第七组" value="第七组"></el-option>
        <el-option key="7" label="第八组" value="第八组"></el-option>
        <el-option key="8" label="第九组" value="第九组"></el-option>
        <el-option key="9" label="第十组" value="第十组"></el-option>
        <el-option key="10" label="第十一组" value="第十一组"></el-option>
        <el-option key="11" label="第十二组" value="第十二组"></el-option>
        <el-option key="12" label="第十三组" value="第十三组"></el-option>
        <el-option key="13" label="第十四组" value="第十四组"></el-option>
        <el-option key="14" label="第十五组" value="第十五组"></el-option>
        <el-option key="15" label="第十六组" value="第十六组"></el-option>
        <el-option key="16" label="第十七组" value="第十七组"></el-option>
      </el-select>

      <el-select
        class="filter"
        v-model="filters.status"
        size="small"
        style="width: 160px"
        @change="search(true)"
      >
        <el-option label="不限事项状态" :value="null"></el-option>
        <el-option
          v-for="data in env.orderStatus"
          :key="data.id"
          :label="data.name"
          :value="data.value"
        ></el-option>
      </el-select>
      <el-select
        class="filter"
        v-model="filters.evaluated"
        size="small"
        style="width: 160px"
        @change="search(true)"
      >
        <el-option label="不限评价状态" :value="null"></el-option>
        <el-option
          v-for="data in env.orderEvaluateds"
          :key="data.id"
          :label="data.name"
          :value="data.value"
        ></el-option>
      </el-select>
      <el-select
        class="filter"
        filterable
        v-model="filters.jbdwId"
        size="small"
        style="width: 160px"
        @change="search(true)"
      >
        <el-option label="不限经办单位" :value="null"></el-option>
        <el-option
          v-for="data in jbdwlist"
          :key="data.id"
          :label="data.name"
          :value="data.id"
        ></el-option>
      </el-select>
      <el-date-picker
        size="small"
        v-model="filters.submitTime"
        type="daterange"
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="提交日期"
        end-placeholder="结束日期">
      </el-date-picker>

      <el-date-picker
        size="small"
        v-model="filters.overTime"
        type="daterange"
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="完成日期"
        end-placeholder="结束日期">
      </el-date-picker>
      <el-button class="filter" type="primary" size="small" @click="search()"
        >查询</el-button
      >
      <el-button class="filter" type="plain" size="small" @click="reset(true)"
        >重置</el-button
      >
    </div>
    <div class="common-list__nect">
      <slot
        name="head"
        :loading="loading"
        :filters="filters"
        :selects="selects"
      ></slot>
    </div>
    <div class="common-list__body">
      <el-table
        ref="table"
        size="medium"
        height="100%"
        :data="list"
        @header-click="onTableHeaderClick"
        @row-click="onTableRowClick"
        @selection-change="onTableSelectionChange"
      >
        <el-table-column
          type="selection"
          align="center"
          v-if="select"
        ></el-table-column>
        <el-table-column label="企业/项目信息" min-width="10">
          <template #default="scope">
            <img
              style="
                float: left;
                margin-right: 10px;
                width: 40px;
                height: 40px;
                object-fit: cover;
              "
              :src="
                scope.row.company.logo.id
                  ? scope.row.company.logo.short
                  : require('../assets/company-avatar.png')
              "
            />
            <a
              :href="'#/staff/corp/company?companyId=' + scope.row.company.id"
              v-if="link && access('staff-corp')"
              >{{ scope.row.company.name }}</a
            >
            <a
              :href="'#/corp/company?companyId=' + scope.row.company.id"
              v-else-if="link && access('corp')"
              >{{ scope.row.company.name }}</a
            >
            <span v-else>{{ scope.row.company.name }}</span>
            <div style="margin-left: 50px; color: #aaa">
              {{ scope.row.company.typeText }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="事项标题" min-width="12">
          <template #default="scope">
            <a
              :href="'#/staff/work/order?orderId=' + scope.row.id"
              v-if="link && access('staff-work')"
              >{{ scope.row.title }}</a
            >
            <a
              :href="'#/officer/work/order?orderId=' + scope.row.id"
              v-else-if="link && access('officer-work')"
              >{{ scope.row.title }}</a
            >
            <a
              :href="'#/work/order?orderId=' + scope.row.id"
              v-else-if="link && access('work')"
              >{{ scope.row.title }}</a
            >
            <span v-else>{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="事项分类" min-width="6">
          <template #default="scope">
            <template v-if="scope.row.tags.length > 0">
              <div v-for="tag in scope.row.tags" :key="tag.id">
                {{ tag.name }}
              </div>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="服务专员" min-width="8">
          <template #default="scope">
            <!--                        <div>{{ scope.row.hand.name }}</div>-->
            <span>{{ scope.row.handler.name }}</span>
            <span style="margin-left: 0.5em; color: #aaa">{{
              scope.row.handler.number
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="调研服务小组" min-width="8">
          <template #default="scope">
            <span>{{ scope.row.fwxz }}</span>
            <!-- <span style="margin-left: 0.5em; color: #aaa">{{
              scope.row.handler.number
            }}</span> -->
          </template>
        </el-table-column>
        <el-table-column label="事项层面" min-width="4">
          <template #default="scope">
            <div v-if="scope.row.level == 1">县级</div>
            <div v-else-if="scope.row.level == 2">市级</div>
            <div v-else-if="scope.row.level == 3">自治区级</div>
            <div v-else>
              <span v-if="scope.row.dept.county.id">县级</span>
              <span v-else-if="scope.row.dept.city.id">市级</span>
              <span v-else-if="scope.row.dept.province.id">自治区级</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="事项状态" min-width="4">
          <template #default="scope">
            <span
              class="el-status--info"
              v-if="scope.row.status === 'created'"
            ></span>
            <span
              class="el-status--danger"
              v-else-if="
                scope.row.status === 'published' ||
                scope.row.status === 'return'
              "
            ></span>
            <span
              class="el-status--warning"
              v-else-if="scope.row.status === 'handling'"
            ></span>
            <span
              class="el-status--success"
              v-else-if="scope.row.status === 'finished'"
            ></span>
            <span>{{ scope.row.statusText }}</span>
          </template>
        </el-table-column>
        <el-table-column label="评价信息" min-width="8">
          <template #default="scope">
            <template
              v-if="
                scope.row.status === 'finished' && scope.row.evaluated === 'yes'
              "
            >
              <div>
                <span>评价打分：</span>
                <span>{{ scope.row.evaluatedStars }}分</span>
              </div>
              <div>
                <span>评价内容：</span>
                <span>{{ scope.row.evaluatedContent }}</span>
              </div>
              <div>
                <span>评价人：</span>
                <span style="margin-right: 0.5em">{{
                  scope.row.evaluatedCreator.name
                }}</span>
                <span
                  v-if="
                    scope.row.evaluatedCreator.employees.length > 0 &&
                    scope.row.evaluatedCreator.employees[0].company.id ===
                      scope.row.company.id
                  "
                  >[{{ scope.row.evaluatedCreator.employees[0].duty }}]</span
                >
              </div>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="提交人/提交时间" min-width="6">
          <template #default="scope">
            <span>{{ scope.row.creator.name }}</span>
            <span style="margin-left: 0.5em; color: #aaa">{{
              scope.row.creator.number
            }}</span>
            <div style="color: #aaa">{{ scope.row.createdAt }}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          :width="160"
          v-if="$slots.body || $scopedSlots.body"
        >
          <template #default="scope">
            <slot
              name="body"
              :loading="loading"
              :filters="filters"
              :data="scope.row"
              :selects="selects"
            ></slot>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div
      class="common-list__foot"
      :class="{ 'common-list__foot--slot': $slots.foot || $scopedSlots.foot }"
    >
      <el-pagination
        background
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="filters.linage"
        :current-page="filters.page"
        :total="filters.total"
        @size-change="onTableLinageChange"
        @current-change="onTablePageChange"
      ></el-pagination>
      <slot
        name="foot"
        :loading="loading"
        :filters="filters"
        :selects="selects"
      ></slot>
    </div>
    <comp-dialog
      title="选择工作队"
      width="720px"
      height="80vh"
      ref="deptPicker"
    >
      <comp-depts style="height: 100%" ref="deptPickerList" expanded>
        <template #body="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-check"
            @click.stop="chooseDept('submit', scope.data)"
            >选择</el-button
          >
        </template>
        <template #foot>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-close"
            @click="chooseDept('end')"
            >放弃</el-button
          >
        </template>
      </comp-depts>
    </comp-dialog>
  </div>
</template>

<script>
import mixin from "../mixin";
import { object, array, string, int, session } from "../util";
export default {
  name: "comp-orders",
  mixins: [mixin],
  props: {
    type: { type: String, default: null },
    select: { type: Boolean, default: false },
    link: { type: Boolean, default: false },
  },
  data: () => ({
    loading: false,
    filters: {
      ids: null,
      type: null,
      companyName: null,
      companyCityId: null,
      companyCountyId: null,
      title: null,
      content: null,
      tagId: null,
      handId: null,
      jbdwId: null,
      evaluated: null,
      status: null,
      level: null,
      fwxz: null,
      linage: 10,
      page: 1,
      total: 0,
      submitTime: undefined,
      overTime: undefined,
    },
    list: [],
    selects: [],
    citys: [],
    countys: [],
    tags: [],
    depts: [],
    jbdwlist: [],
  }),
  methods: {
    reset(deep) {
      let data = deep
        ? {}
        : object(
            session([
              this.env.key,
              this.$options.name,
              "filters",
              this.$route.fullPath,
            ])
          );
      this.filters = Object.assign(this.$options.data().filters, data);
      this.depts = array(
        session([
          this.env.key,
          this.$options.name,
          "depts",
          this.$route.fullPath,
        ])
      );
      this.search(true);
    },
    validate() {
      let filters = this.filters;
      let depts = this.depts;
      filters.ids = null;
      filters.type = this.type;
      filters.handId =
        string(() => depts.find((dept) => dept.id === filters.handId).id) ||
        null;
      filters.total = Math.max(int(filters.total), 0);
      filters.linage = Math.max(int(filters.linage), 1);
      filters.page = Math.max(
        Math.min(int(filters.page), Math.ceil(filters.total / filters.linage)),
        1
      );
      session(
        [this.env.key, this.$options.name, "filters", this.$route.fullPath],
        filters
      );
      session(
        [this.env.key, this.$options.name, "depts", this.$route.fullPath],
        depts
      );
    },
    onTableHeaderClick() {
      this.select && this.$refs.table.toggleAllSelection();
    },
    onTableRowClick(row) {
      this.select && this.$refs.table.toggleRowSelection(row);
    },
    onTableLinageChange(value) {
      this.filters.linage = value;
      this.search(true);
    },
    onTablePageChange(value) {
      this.filters.page = value;
      this.search(true);
    },
    onTableSelectionChange(selects) {
      this.filters.ids = selects.map((data) => data.id);
      this.selects = selects;
    },
    chooseDept(action, dept) {
      if (this.loading) return;
      let filters = this.filters;
      if (!action || action === "start") {
        this.$refs.deptPicker.init();
        this.$nextTick(() => this.$refs.deptPickerList.init());
      } else if (action === "submit") {
        let index = this.depts.findIndex((target) => target.id === dept.id);
        if (index > -1) this.depts.splice(index, 1);
        filters.handId = dept.id;
        this.depts.push({ id: dept.id, name: dept.name });
        this.chooseDept("end");
        this.search(true);
      } else if (action === "end") {
        this.$refs.deptPicker.close();
      }
    },
    search(clean) {
      if (this.loading) return;
      if (clean) this.list == [];
      if (clean) this.selects = [];
      let filters = this.filters;
      console.log(filters);
      this.validate();
      this.loading = true;
      // console.log(filters);
      filters.createdTimeStart = filters.submitTime?.[0];
      filters.createdTimeEnd = filters.submitTime?.[1];

      filters.completeTimeStart = filters.overTime?.[0];
      filters.completeTimeEnd = filters.overTime?.[1];
      console.log('search',filters)
      this.plugins.user.getOrders(filters).then((res) => {
        this.loading = false;
        this.list = [];
        this.selects = [];
        this.$nextTick(() => this.$refs.table.doLayout());
        if (res.code === 0) {
          let data = res.data;
          if (data.page > 1 && data.list.length === 0) {
            filters.total = 0;
            this.search();
          } else {
            filters.total = data.total;
            this.list = data.list.map((order) => {
              let creator = order.evaluatedCreator;
              let employees = creator.employees.splice(0);
              for (let employee of employees)
                employee.company.id === order.company.id &&
                  creator.employees.push(employee);
              return order;
            });
            this.validate();
            for (let key in data.stats) {
              let navs = this.$root.$refs.navbar.leftbar.navs;
              let role = this.profile.role;
              if (role === "holder" || this.profile.isAdmin > 0) {
                let nav = navs.find((nav) => nav.name.includes(key));
                if (nav) nav.text = string(data.stats[key]);
              } else if (role === "staff") {
                let nav = navs.find(
                  (nav) => nav.name.includes(key)
                );
                if (nav) nav.text = string(data.stats[key]);
              } else if (role === "officer") {
                let nav = navs.find(
                  (nav) => nav.name.includes(key)
                );
                if (nav) nav.text = string(data.stats[key]);
              }
            }
          }
        } else {
          filters.total = 0;
          this.validate();
          this.plugins.modal.toast(
            "列表加载失败<br>" + res.code + "：" + res.msg,
            "error"
          );
        }
      });
    },
    init() {
      this.loading = true;
      this.plugins.user
        .call(async () => {
          this.citys = this.plugins.user.citys;
          this.countys = this.plugins.user.countys;
          this.plugins.user
            .getjbdw({ linage: 10000000, page: 1 })
            .then((res) => {
              console.log(res);
              this.jbdwlist = res.data.list;
            });
          this.tags =
            this.tags.length > 0
              ? this.tags
              : await this.plugins.user
                  .getOrderOfTags()
                  .then((res) => array(res.data));
        })
        .then(() => {
          this.loading = false;
          this.reset();
        });
    },
  },
};
</script>

<style lang="scss">
.comp-orders {
  overflow: hidden;
}
</style>
